package com.ld.businesscard_manage.controller.user;

import com.alibaba.excel.EasyExcel;
import com.ld.businesscard_manage.bean.AllCardsExcel;
import com.ld.businesscard_manage.bean.BusinessCard;
import com.ld.businesscard_manage.bean.MyCardsExcel;
import com.ld.businesscard_manage.bean.User;
import com.ld.businesscard_manage.service.BusinessCardService;
import com.ld.businesscard_manage.service.impl.BusinessCardServiceImpl;
import com.ld.businesscard_manage.utils.ExcelUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@WebServlet("/downloadExcel")

public class DownloadController extends HttpServlet {
	private BusinessCardService cardService = new BusinessCardServiceImpl();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		User user =(User)req.getSession().getAttribute("user");

		if(user.getStatus() == 1){
			List<BusinessCard> list = cardService.getAllCards();
			resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			resp.setCharacterEncoding("utf-8");
			// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
			String fileName = URLEncoder.encode("名片信息", "UTF-8").replaceAll("\\+", "%20");
			resp.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
			EasyExcel.write(resp.getOutputStream(), AllCardsExcel.class).sheet("名片信息").doWrite(ExcelUtil.data(list));
		}else {
			List<BusinessCard> list = cardService.getMyCards(user.getUsername());
			resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			resp.setCharacterEncoding("utf-8");
			// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
			String fileName = URLEncoder.encode("我的名片", "UTF-8").replaceAll("\\+", "%20");
			resp.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
			EasyExcel.write(resp.getOutputStream(), MyCardsExcel.class).sheet("我的名片").doWrite(ExcelUtil.myData(list));
		}
	}
}
